package org.shzhyun.tools;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class FindHTMLFiles {

    public static void main(String[] args) {
        // 定义要遍历的根目录
        String rootDirectory = "/Users/gds/project2025/qb/Questions";
        // 定义输出文件路径
        String outputFilePath = "/Users/gds/project2025/qb/demo.txt";

        try (FileWriter writer = new FileWriter(outputFilePath)) {
            // 开始遍历
            traverseDirectory(new File(rootDirectory), rootDirectory, writer);
            System.out.println("文件路径已成功写入到 " + outputFilePath);
        } catch (IOException e) {
            System.err.println("写入文件时发生错误: " + e.getMessage());
        }
    }

    /**
     * 递归遍历文件夹
     *
     * @param currentFile 当前文件或文件夹
     * @param rootPath    根目录路径
     * @param writer      FileWriter 对象，用于写入文件
     * @throws IOException 如果写入文件时发生错误
     */
    private static void traverseDirectory(File currentFile, String rootPath, FileWriter writer) throws IOException {
        if (currentFile.isDirectory()) {
            // 如果是文件夹，递归遍历子文件和子文件夹
            File[] files = currentFile.listFiles();
            if (files != null) {
                for (File file : files) {
                    traverseDirectory(file, rootPath, writer);
                }
            }
        } else if (currentFile.isFile() && currentFile.getName().equals("question.html")) {
            // 如果是文件且文件名为 a.html，获取相对路径并写入文件
            String relativePath = getRelativePath(currentFile, rootPath);
//            System.out.println(relativePath);
//            writer.write("http://localhost/Questions/"+relativePath + System.lineSeparator());

            writer.write("<a href=\"http://localhost/Questions/"
                    +relativePath+"\" target=\"_blank\">"+relativePath+"</a><br>" + System.lineSeparator());
        }
    }

    /**
     * 获取文件相对于根目录的相对路径
     *
     * @param file     当前文件
     * @param rootPath 根目录路径
     * @return 文件的相对路径
     */
    private static String getRelativePath(File file, String rootPath) {
        String absolutePath = file.getAbsolutePath();
        return absolutePath.substring(rootPath.length() + 1);
    }
}
